<?php

namespace app\index\controller;

use think\Cache;
use think\cache\driver\Redis;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Request;
use think\Session;

class Login extends Controller
{
    public function index()
    {
        return view();
    }

    public function doLogin()
    {
        $request = Request::instance();
        $data = $request->post();
        $data['pass'] = md5($data['pass']);

        // 先查询手机号码存不存在
        $res1 = Db::name('huser')
            ->field(['id','status'])
            ->where('tel', $data['tel'])
            ->whereor('email',$data['tel'])
            ->whereor('name',$data['tel'])
            ->find();
        if ($res1['status'] !== 0) {
            return $this->error('访问被限制!');
        }
//        var_dump($res1);die;
        // 判断该用户是否被限制
        if (isset(Cache::get('user'.$res1['id'])['time'])) {
            if (Cache::get('user'.$res1['id'])['time'] == 4) {
//                var_dump(Cache::get('user'.$res1)['time']);die;
                return $this->error('您的账户被限制,请稍后再试!');
            }
        }


        if ($res1) {
            $res2 = Db::name('huser')
                ->field('id')
                ->where('pass', $data['pass'])
                ->whereor('tel', $data['tel'])
                ->whereor('email',$data['tel'])
                ->whereor('name',$data['tel'])
                ->find();
            // 如果用户名存在,密码错误,则记入缓存
            if ($res2) {
                // 存cookie和session
                if (array_key_exists('rem',$data)) {
                    // 存cookie
                    Session::set('user',['tel'=>$data['tel'],'pass'=>$data['pass']]);
                    Cookie::set('user',['tel'=>$data['tel'],'pass'=>$data['pass']]);
                } else {
                    // 存session
                    Session::set('user',['tel'=>$data['tel'],'pass'=>$data['pass']]);
                }
                return $this->redirect(url('index/index/index'));
            } else {
                // 登录失败次数限制
                $this->limitLogin($res1['id']);
                return $this->error('登录失败!');
            }
        } else {
            return $this->error('您的账户还没有注册哦,快去注册吧...',url('index/register/index'));
        }
    }

    // 登录失败次数限制
    private function limitLogin($uid)
    {
        if (isset(Cache::get('user'.$uid)['time'])) {
            if (Cache::get('user'.$uid)['time'] < 3) {
                $time = Cache::get('user'.$uid)['time'];
//                var_dump(Cache::get('user'.$uid)['time']);
                Cache::set('user'.$uid,['time'=>$time+1]);
            } else {
                Cache::set('user'.$uid,['time'=>4],300);
                return $this->error('密码错误多次,请5分钟后再试!!!');
            }
        } else {
            Cache::set('user'.$uid,['time'=>1]);
        }
    }


    // 注销
    public function logout()
    {
        Session::pull('user');
    }
}
